package com.modules.controller.sys;

import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.common.controller.MyController;
import com.common.util.ImageUtil;
import com.common.vo.Result;


/**
 * 文件上传
 * @author yyq
 *
 */
@Controller
@RequestMapping("/upload")
public class FileControl extends MyController<Object>{

	
	/**
	 * 头像图片
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unused")
	@ResponseBody
	@RequestMapping("/userImg")
	public Result<?> uploadjzjzImg(HttpServletRequest request){
		String idcard = request.getParameter("idcard");
		ServletContext sc = request.getServletContext();	
		String path = sc.getRealPath("/upload/photo/jzjz/"+getUser().getOid());
		if (ImageUtil.serverType == 1) {
			path = ImageUtil.NGINXPATH + "/upload/photo/jzjz/"+getUser().getOid();
		}
		FileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload su = new ServletFileUpload(factory);
		List<FileItem> items = null;
		StringBuffer sb = new StringBuffer();
		try {
			items = su.parseRequest(request);
			Iterator<FileItem> iter = items.iterator();
			boolean state=false;
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					try {
						state = true;
						String yName = item.getName();
						String fileName = idcard+".jpg";
						ImageUtil.processUploadFileGenerateSmall(item, path, fileName);
						sb.append("/upload/photo/jzjz/"+getUser().getOid()+"/"+fileName);
					} catch (Exception e) {
						state = false;
					}  
				}
			}
			if (state) {
				return Result.success(sb.toString(), "上传成功");
			}else{
				return Result.fail("上传失败");
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
			return Result.fail("系统异常");
		}
	}
	
	
	
	
	
	

}
